<?php
        /*
         * @version $Id: sitemap.php,v 1.1 2010/11/12 17:36:24 marco_manti
         * @package http://www.gisa.by
         * @copyright (C) 2006 - 2010 marco_manti(R)
         * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
         * @description Script generate sitemap for site http://www.gisa.by
         */

        ini_set("max_execution_time", "240");
        
        require_once(dirname(dirname(__FILE__)).'/includes/library.php');

        // init global classes
        $dbo = new DB();
        $helper = new HELPER();
        $config = new CONFIG();
        
        // globals
        $now = date('c');
        $endline = chr(13).chr(10);
        $counter = 0;
        $today = date('Y-m-d H:i');
        $month = date('c', strtotime(date('Y-m') . '-01'));
        $title = ' GENERATE SITEMAP: ';
        $email_title = 'GISA.by ::' . $title;
        $email = $config->server_root;
        $redirections = array();
        $logmsg = $mysqlerrlog = '';

        // mail headers
        $headers  = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=windows-1251\r\n";
        $headers .= "From: GISA.by <gisaby@gmail.com>\r\n";
        $headers .= "X-Mailer: PHP/" . phpversion();
        
        // get SEF representation of links
        function getSEFLink($link) {
            global $redirections, $config;

            if ($link == '' || $link == $config->liveSite) return $config->liveSite;

            if (array_key_exists($link, $redirections)) return $config->liveSite.'/'.$redirections[$link];
            else return $config->liveSite.'/'.$link;
        }

        // generate sitemap item
        function addSitemapItem($link, $lastmod = '', $priority = 1.0, $changefreq = 'daily') {
            global $endline, $counter, $now, $config;

            if ($link == '') $link = $live_site;
            if ($lastmod == '') $lastmod = $now;

            $item .= '  <url>'.$endline;
            $item .= '    <loc>'.getSEFLink($link).'</loc>'.$endline;
            $item .= '    <lastmod>'.$lastmod.'</lastmod>'.$endline;
            $item .= '    <priority>'.sprintf('%01.1f', $priority).'</priority>'.$endline;
            $item .= '    <changefreq>'.$changefreq.'</changefreq>'.$endline;
            $item .= '  </url>'.$endline;

            $counter++;
            return $item;
        }

        // get last modified date for EA categories
        function getLastModified($cat = null) {
            global $dbo;

            if ($cat)
                $query = "SELECT timestamp FROM rlt_estateagent WHERE cat = $cat ORDER BY timestamp DESC";
            else
                $query = "SELECT timestamp FROM rlt_estateagent ORDER BY timestamp DESC";

            $timestamp = $dbo->getResult($query);
            $timestamp = date('c', strtotime($timestamp));
            return ($timestamp ? $timestamp : date('c'));
        }

        // connect to DB
        if (!$dbo->connect()) {
            $logmsg .= $today.$title.'ERROR - connect to database ['.$dbo->error().'];'.$endline;
            $mysqlerrlog .= $today.$title.' '.$dbo->error().$endline;
            mail($email, $email_title, 'ERROR - connect to database ['.$dbo->error().'];', $headers);
        }

        // get array of sef links
        $query = "SELECT newurl, oldurl
                  FROM rlt_redirection
                  WHERE oldurl LIKE '%database%'
                  OR newurl LIKE '%com_agency%' OR newurl LIKE '%com_comprofiler%' OR newurl LIKE '%showEO%'OR newurl LIKE '%com_login%'
                  ORDER BY cpt DESC
                  LIMIT 0, 5000 ";
        
        $objects = $dbo->getObjectsArray($query);
        if (!$objects) {
            $logmsg .= $today.$title.'ERROR - getting fields from _redirections ['.$dbo->error().'];'.$endline;
            $mysqlerrlog .= $today.$title.' '.$dbo->error().$endline;
            mail($email, $email_title, 'ERROR - getting fields from _redirections ['.$dbo->error().'];', $headers);
        } else {
            foreach($objects as $item) {
                $redirections[$item->newurl] = $item->oldurl;
            }
        }

        // header
        $body .= '<?xml version="1.0" encoding="UTF-8"?>'.$endline;
        $body .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">'.$endline;
        
        // main page link
        $body .= addSitemapItem('', getLastModified(), 0.9);

        // db page link
        $body .= addSitemapItem('index.php?option=com_estateagent&act=cat&task=showCE&Itemid=14', getLastModified(), 1, 'hourly');
        
        // search page link
        $body .= addSitemapItem('index.php?option=com_estateagent&task=search&act=easearch&Itemid=13', $month, 0.8, 'monthly');
        
        // archive page link
        $body .= addSitemapItem('index.php?option=com_estateagent&act=cat&task=showARCH&Itemid=69', getLastModified(), 0.8, 'daily');
        
        // login page link
        $body .= addSitemapItem('index.php?option=com_login', $month, 0.7, 'monthly');
        
        // register page link
        $body .= addSitemapItem('index.php?option=com_comprofiler&task=registers&Itemid=14', $month, 'monthly');
        
        // agency register page link
        $body .= addSitemapItem('index.php?option=com_agency&Itemid=86', $month, 0.7, 'monthly');
        
        // articles links
        $query = "SELECT id, title_alias, modified FROM rlt_content";
        $objects = $dbo->getObjectsArray($query);
        if (!$objects) {
            $logmsg .= $today.$title.'ERROR - getting fields from _content ['.$dbo->error().'];'.$endline;
            $mysqlerrlog .= $today.$title.' '.$dbo->error().$endline;
            mail($email, $email_title, 'ERROR - getting fields from _content ['.$dbo->error().'];', $headers);
        }

        if (count($objects) > 0 ) {
            foreach($objects as $item) {
               $url = $item->title_alias.'.html';
               $lastmod = date('c', strtotime($item->modified));
               $priority = 0.8;
               $changefreq = 'weekly';
               $body .= addSitemapItem($url, $lastmod, $priority, $changefreq);
            }
        } else {
            $logmsg .= $today.$title.'ERROR - estateagent return empty result ['.$dbo->error().'];'.$endline;
            $mysqlerrlog .= $today.$title.' '.$dbo->error().$endline;
            mail($email, $email_title, 'ERROR - estateagent return empty result ['.$dbo->error().'];', $headers);
        }

        // categories links
        $query = "SELECT cat AS id, MAX(timestamp) AS timestamp FROM rlt_estateagent GROUP BY cat";
        $objects = $dbo->getObjectsArray($query);
        if (!$objects) {
            $logmsg .= $today.$title.'ERROR - getting fields from estateagent categories ['.$dbo->error().'];'.$endline;
            $mysqlerrlog .= $today.$title.' '.$dbo->error().$endline;
            mail($email, $email_title, 'ERROR - getting fields from estateagent categories ['.$dbo->error().'];', $headers);
        }

        if (count($objects) > 0 ) {
            foreach($objects as $item) {
               $url = 'index.php?option=com_estateagent&act=cat&task=showCE&id='.$item->id.'&Itemid=14';
               $lastmod = getLastModified($item->id);
               $priority = 0.7;
               $changefreq = 'daily';

               $body .= addSitemapItem($url, $lastmod, $priority, $changefreq);
            }
        } else {
            $logmsg .= $today.$title.'ERROR - estateagent return empty result ['.$dbo->error().'];'.$endline;
            $mysqlerrlog .= $today.$title.' '.$dbo->error().$endline;
            mail($email, $email_title, 'ERROR - estateagent return empty result ['.$dbo->error().'];', $headers);
        }

        // database links
        $query = "SELECT * FROM rlt_estateagent";
        $objects = $dbo->getObjectsArray($query);
        if (!$objects) {
            $logmsg .= $today.$title.'ERROR - getting fields from estateagent ['.$dbo->error().'];'.$endline;
            $mysqlerrlog .= $today.$title.' '.$dbo->error().$endline;
            mail($email, $email_title, 'ERROR - getting fields from estateagent ['.$dbo->error().'];', $headers);
        }

        if (count($objects) > 0 ) {
            foreach($objects as $item) {
               $url = 'index.php?option=com_estateagent&act=object&task=showEO&Itemid=14&id='.$item->id;
               $lastmod = date('c', strtotime($item->timestamp));

               $priority = $helper->getEAPriority($item);
               $changefreq = 'weekly';

               $body .= addSitemapItem($url, $lastmod, $priority, $changefreq);
            }
        } else {
            $logmsg .= $today.$title.'ERROR - estateagent return empty result ['.$dbo->error().'];'.$endline;
            $mysqlerrlog .= $today.$title.' '.$dbo->error().$endline;
            mail($email, $email_title, 'ERROR - estateagent return empty result ['.$dbo->error().'];', $headers);
        }

        // footer
        $body .= '</urlset>'.$endline;

        if ($logmsg == '') {
            $logmsg .= $today.$title.'SUCCESS - '.$counter.' links generated;'.$endline;
        }

        // write generated sitemap
        $helper->writeToFile($body, 'w', 'sitemap.xml');

        // delete old sitemap
        unlink($config->absPath.'/sitemap.xml');

        // copy new sitemap
        $res = copy($config->absPath.'/cron/sitemap.xml', $config->absPath.'/sitemap.xml');
        if ($res) {
            $logmsg .= $today.$title.'SUCCESS - copy sitemap;'.$endline;
        } else {
            $logmsg .= $today.$title.'ERROR - copy sitemap ['.$res.'];'.$endline;
            mail($email, $email_title, 'ERROR - copy sitemap ['.$res.'];', $headers);
        }

        // write state to log
        $helper->writeToFile($logmsg);
        
        // write SQL error if present
        if ($mysqlerrlog != '') {
            $helper->writeToFile($mysqlerrlog, 'a+', 'mysql_errors.log');
        }
?>